<?php 

/**
 * 拼团管理
 * @Author      jiating
 * @DateTime    2018-05-16
 */

namespace app\admin\controller;

use app\common\BaseHelper;
use \think\Request;
use app\admin\model\Groupproduct;
use app\admin\model\Producttype;
use app\admin\model\Product;
use app\admin\model\Productspecgroups;
use app\admin\model\Store;
use app\admin\model\Groupdetail;
use app\admin\model\Wxcomponentconf;
use app\common\model\Order;

class Group extends Base{

    public function __construct() {
        parent::__construct();
        $this->model = new Groupproduct();
    }

    public function index(){
        if(!$this->checkStore()) {
            return $this->fetch('public/alert');
        }
        
        $request = Request::instance();
        $param = $request->param();

        $store = Store::where(['tenantId'=>session('TENANT_ID')])->select();
        $type = Producttype::where(['tenantId'=>session('TENANT_ID')])->select();
        $storeId = empty($param) ? $store[0]['id'] : $param['storeId'];

        $this->assign('store',$store);
        $this->assign('type',$type);
        $this->assign('storeId',$storeId);
        return $this->fetch();
    }

    public function indexApi() {
        $request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数
        $storeId = $param['storeId'];
        if(empty($param['search']['value'])) {  //排序展示，默认按排序字段由小到大
            $order = 'sort';
        }else{
            $order = json_decode($param['search']['value'],true);
            if($order['order'] == 'sell') {  //TODO 按热卖数量排序
                $order = 'create_time';
            } else if($order['order'] == 'create_time'){  //按事件降序
                $order = 'create_time DESC';
            }else{  //首页推荐的在先
                $order = $order['order'];
            }
        }

        $where = [
            'storeId' => $storeId,
            'status' => ['neq', '2']
        ];
        $list = $this->model->field('a.id,a.recommendation,b.imgUrl,b.title,b.currentPrice,b.id productId')->alias('a')->join('product b','a.productId=b.id')->where($where)->limit($start,$length)->order($order)->select();
        $count = $this->model->where($where)->count();

        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($res);
    }

    // 删除拼团商品-逻辑删除
    public function groupDel(){
        $request = Request::instance();
        $id = $request->param('id');  //拼团ID
        $storeId = $request->param('storeId');

        $wxcomponent = Wxcomponentconf::alias('a')->join('wxframeconf b','a.frameId=b.id')->where(['linkType'=>'6','linkId'=>$id,'b.storeId'=>$storeId])->find();
        if($wxcomponent) {
            return json(['code'=>'2','message'=>'此拼团被选为首页展示链接，不可删除']);
        }

        $find = Order::where(['spellGroupId'=>$id,'storeId'=>$storeId,'linkType'=>1])->where('status','not in',[4,5,7])->find();
        if($find) {
            return json(['code'=>'2','message'=>'此商品有未完成订单，不能删除']);
        }

        $upd = $this->model->where('id',$id)->update(['status'=>2]);
        if($upd) {
            return json(['code'=>'1','message'=>'删除成功']);
        }
        return json(['code'=>'2','message'=>'删除失败，请重试']);
    }

    // 设置首页推荐
    public function recommend() {
        $request = Request::instance();
        $id = $request->param('id');  //拼团ID
        $recommendation = $request->param('recommendation');  //是否推荐
        $upd = $this->model->where('id',$id)->update(['recommendation'=>$recommendation]);
        if($upd) {
            return json(['code'=>'1','message'=>'设置成功']);
        }
        return json(['code'=>'2','message'=>'推荐失败，请重试']);
    }

    //保存选中商品到groupproduct表
    public function setGroup(){
        $request = Request::instance();
        $param = $request->param();
        // dump($param);die;

        $id = $param['productId'];
        $storeId = $param['storeId'];

        $product = Product::where('id',$id)->find();
        if(empty($product['groupPrice'])) {  //检查是否已设置拼团价
            return json(['code'=>'2','message'=>'此商品尚未设置拼团价，请到商品管理中设置']);
        }
        if($product['specClass'] == '2') {  //多规格商品，取所有拼团价
            $spec = Productspecgroups::where('productId',$id)->select();
            $product['sub'] = $spec;
            $product['spec'] = json_decode($product['spec'],true);
        }
        // return json($product);
        $group = $this->model->where(['productId'=>$id,'storeId'=>$storeId])->find();

        $this->assign('product',$product);
        $this->assign('group',$group);
        $this->assign('storeId',$storeId);

        return $this->fetch('setgroup');
    }

    public function setGroupSave() {
        $request = Request::instance();
        $param = $request->param();
        // return $param;
        if($param['id']) {  //编辑
            $param['update_time'] = time();
            $param['status'] = 1;
            // return $param;
            $save = $this->model->update($param);
        } else {  //添加
            $param['id'] = get_uniqid_id();
            $param['create_time'] = time();
            $param['update_time'] = time();
            $save = $this->model->insert($param);
        }
        if($save) {
            return json(['code'=>'1','message'=>'设置成功']);
        }
        return json(['code'=>'2','message'=>'保存失败，请重试']);
    }

    //查看所有商品开团记录
    public function recordList() {
        $request = Request::instance();
        $storeId = $request->param('storeId');  //门店ID
        $groupId = $request->param('groupId');  //拼团商品表ID
        $store = Store::where('id',$storeId)->find();
        // dump($list);
        $this->assign('storeId',$storeId);
        $this->assign('groupId',$groupId);
        $this->assign('store',$store);
        return $this->fetch();
    }

    public function recordListApi() {
        $request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数
        $storeId = $param['storeId']; //门店ID
        $where = ['a.storeId'=>$storeId];
        if(isset($param['groupId']) && $param['groupId']) {
            $where['groupId'] = $param['groupId'];
        }

        if(!empty($param['search']['value'])) {  //按商品名称搜索
            $search = json_decode($param['search']['value'],true);
            $where['title'] = ['like','%'.$search['name'].'%'];
        }

        $list = Groupdetail::distinct(true)->field('a.*,b.groupSuccCount,c.title,c.imgUrl')->alias('a')->join('groupproduct b','a.groupId=b.id')->join('product c','b.productId=c.id')->where($where)->group('unigroupId')->limit($start,$length)->order('create_time DESC')->select();
        foreach ($list as $k => $v) {
            $num = Groupdetail::where('unigroupId',$v['unigroupId'])->count();
            $list[$k]['count'] = $num;
        }
        $count = Groupdetail::distinct(true)->alias('a')->join('groupproduct b','a.groupId=b.id')->join('product c','b.productId=c.id')->where($where)->group('unigroupId')->field('a.*,b.groupSuccCount,c.title,c.imgUrl')->count();

        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
            'test' => $param
        ];
        return json($res);
    }

    //某个拼团详情
    public function groupMember() {
        $request = Request::instance();
        $param = $request->param();  //拼团唯一标识ID
        $id = $param['id'];

        $list = Groupdetail::field('a.id,a.orderId,o.orderNO,a.unigroupId,u.name,u.mobile,o.total_count,o.total,a.create_time')->alias('a')->join('order o','a.orderId=o.id')->join('user u','a.userId=u.id')->where('unigroupId',$id)->order('create_time')->select();
        $count = Groupdetail::where('unigroupId',$id)->count();

        $res = [
            'status' => '1',
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($res);


    }


}